package com.stone.zeus.component.grpc.test.benchmark;


import com.google.common.collect.Lists;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author fujianjian
 * @date 2023/5/10 17:07
 **/
// 指定吞吐量模式
@BenchmarkMode(Mode.Throughput)
// 指定测试结果使用的时间单位
@OutputTimeUnit(TimeUnit.SECONDS)
// 为每个测试线程分配一个实例， 相当于spring中的@scope
@State(Scope.Thread)
@Fork(2)
// 先进行4次预热
@Warmup(iterations = 1)
// 指定进行10次测试
@Measurement(iterations = 2)
public class ListPerferenceBenchMark {

    @Param(value = {"20", "40", "100", "1000"})
    private int count;

    private List<Integer> arrayList;
    private List<Integer> linkList;

    @Setup(Level.Trial)
    public void init() {
        arrayList = Lists.newArrayList();
        linkList = Lists.newLinkedList();
        for (int i = 0; i < count; i++) {
            arrayList.add(i);
            linkList.add(i);
        }
    }

    @Benchmark
    public void arrayTraverse() {
        for (int i = 0; i < count; i++) {
            arrayList.get(i);
        }
    }

    @Benchmark
    public void linkTraverse() {
        for (int i = 0; i < count; i++) {
            linkList.get(i);
        }
    }

    @TearDown(Level.Trial)
    public void tearDown() {
        arrayList.clear();
        linkList.clear();
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(ListPerferenceBenchMark.class.getSimpleName()).build();
        new Runner(opt).run();
    }
}
